import { message, Spin } from 'antd';
import React, { Fragment, useCallback, useContext, useEffect, useState } from 'react'
import { reqCurriculum, reqSearchCur } from '@/api/api';
import { Context } from '@/App';
import './trainingPlan.less'

import TrainingPlanList from '@/components/TrainingPlanUI/TrainingPlanList';
import TrainingPlanSearch from '@/components/TrainingPlanUI/TrainingPlanSearch'


export default function TrainingPlan() {
  const [curriculum, setCurriculum] = useState()
  const [loading, setLoading] = useState(true)
  const context = useContext(Context);

  const{role} = context

  const geCurriculum = useCallback((data) => {
    setLoading(true)
    reqCurriculum(data).then(
      res => {
        if (res.status === 200) {
          setLoading(false)
          setCurriculum(res.data)
        }
        if (res.status === 201) {
          message.error("查询不到该专业课程！")
          setCurriculum(null)
        }
      },
      rej => { }
    )
  }, [])

  // 加载是获取数据
  useEffect(() => {
    if (role !== null) {
      geCurriculum(role)
    }
  }, [role])

  const onSearch = (values) => {
    // 获取查询课程
    reqSearchCur({values,role}).then(
      res => {
        if (res.status === 200) {
          setCurriculum(res.data)
        } else if (res.status === 201) {
          message.error("查询不到课程信息")
        }
      },
      rej => {
        console.log(rej);
      }
    )
  };

  return (
    <Fragment>
      {
        loading ? <Spin size='large' className='loading' /> :
          <>
            <div className='trainingPlan-box'>
              <div className="trainingPlan-select">
                <TrainingPlanSearch
                  onFinish={onSearch}
                />
              </div>
              <div className='trainingPlan-table'>
                <TrainingPlanList curriculum={curriculum} />
              </div>
            </div>
          </>
      }
    </Fragment>
  )
}
